<template>
    
    <div class="app-container">
            <!-- 新增按钮 -->
            <div style="margin-bottom: 20px;">
            <el-button type="primary" @click="handleAdd">新增</el-button>
        </div>
        <!-- 搜素框 -->
        <el-form :inline="true" :model="searchForm" class="search-form">
    <el-form-item label="商品ID">
        <el-input v-model="searchForm.id" placeholder="请输入商品ID"></el-input>
    </el-form-item>
    <el-form-item label="商品名称">
        <el-input v-model="searchForm.merchandise" placeholder="请输入商品名称"></el-input>
    </el-form-item>
    <el-form-item label="价格区间">
    <el-input
        v-model="searchForm.minPrice"
        placeholder="最低价"
        style="width: 100px;"
        @input="validatePrice('minPrice')"
    ></el-input>
    至
    <el-input
        v-model="searchForm.maxPrice"
        placeholder="最高价"
        style="width: 100px;"
        @input="validatePrice('maxPrice')"
    ></el-input>
</el-form-item>
    <el-form-item label="所属店铺">
        <el-input v-model="searchForm.affiliation" placeholder="请输入店铺名称"></el-input>
    </el-form-item>
    <el-form-item label="状态">
        <el-select v-model="searchForm.status" placeholder="请选择状态">
            <el-option label="全部" value=""></el-option>
            <el-option label="是" value="Y"></el-option>
            <el-option label="否" value="N"></el-option>
        </el-select>
    </el-form-item>
    <el-form-item label="类型">
        <el-input v-model="searchForm.type" placeholder="请输入类型"></el-input>
    </el-form-item>
    <el-form-item label="创建时间">
    <el-select v-model="searchForm.createTime" placeholder="请选择创建时间">
        <el-option label="全部" value="all"></el-option>
        <el-option label="近三个月" value="lastThreeMonths"></el-option>
        <el-option label="今年内" value="thisYear"></el-option>
        <el-option label="2022年" value="2022"></el-option>
        <el-option label="2021年" value="2021"></el-option>
        <el-option label="2020年" value="2020"></el-option>
        
    </el-select>
</el-form-item>
    <el-form-item>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
       
    </el-form-item>
</el-form>
        <!--  -->
        <el-table :data="typeList" style="width: 100%" row-key="id" border>
            <!-- id -->
            <el-table-column prop="id" label="ID" sortable width="180">
            </el-table-column>
            <el-table-column prop="merchandise" label="商品" sortable width="150">
            </el-table-column>
            <el-table-column prop="price" label="价格" sortable width="90">
            </el-table-column>
            <el-table-column prop="packingFee" label="打包费" sortable width="90">
            </el-table-column>
            <el-table-column prop="inventory" label="库存" sortable width="80">
            </el-table-column>
            <el-table-column prop="soldMonthly" label="月售" sortable width="80">
            </el-table-column>
            <el-table-column prop="affiliation" label="所属店铺" align="center"  width="100">
            </el-table-column>
            <el-table-column prop="status" label="状态" align="center" width="90">
                <template slot-scope="scope">
                    <el-tag :type="scope.row.status == 'Y' ? '' : 'danger'">
                        <span>{{ scope.row.status == 'Y' ? '是' : '否' }}</span>
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="category" label="分类"  width="80">
            </el-table-column>
            <el-table-column prop="image" label="图片"  width="180">
    <template slot-scope="scope">
        <img :src="scope.row.image" alt="图片" style="width: 100px; height: auto;" />
    </template>
</el-table-column>
            <el-table-column prop="createTime" label="创建时间"> </el-table-column>
            <el-table-column label="操作" width="180">
                <template slot-scope="scope">
                    <div style="display: flex; flex-direction: column; gap: 8px;">
            <el-button size="mini" type="primary" @click="viewDetails(scope.row)">查看详情</el-button>
            <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
            <el-button size="mini" type="success" @click="placeOrder(scope.row)">下单</el-button>
        </div>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页组件 -->
        <el-pagination
            background
            layout="prev, pager, next, sizes, total"
            :total="total"
            :page-size="pageSize"
            :current-page="pageNum"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        >
        </el-pagination>

    <el-dialog title="新增" :visible.sync="dialogFormVisible">
            <el-form :model="form" label-width="80px">
    <el-form-item label="商品名称">
        <el-input v-model="form.merchandise" placeholder="请输入商品名称"></el-input>
    </el-form-item>
    <el-form-item label="价格">
        <el-input v-model="form.price" type="number" placeholder="请输入价格"></el-input>
    </el-form-item>
    <el-form-item label="打包费">
        <el-input v-model="form.packingFee" type="number" placeholder="请输入打包费"></el-input>
    </el-form-item>
    <el-form-item label="库存">
        <el-input v-model="form.inventory" type="number" placeholder="请输入库存"></el-input>
    </el-form-item>
    <el-form-item label="月售">
        <el-input v-model="form.soldMonthly" type="number" placeholder="请输入月售"></el-input>
    </el-form-item>
    <el-form-item label="所属店铺">
        <el-input v-model="form.affiliation" placeholder="请输入所属店铺"></el-input>
    </el-form-item>
    <el-form-item label="状态">
        <el-select v-model="form.status" placeholder="请选择状态">
            <el-option label="是" value="Y"></el-option>
            <el-option label="否" value="N"></el-option>
        </el-select>
    </el-form-item>
    <el-form-item label="图片">
        <el-upload
            class="upload-demo"
            action=""
            :http-request="handleUpload"
            list-type="picture-card"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
        >
            <i class="el-icon-plus"></i>
        </el-upload>
    </el-form-item>
</el-form>
           
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="addType">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
// 导入接口方法
import { getList, addType, deleteType, typeInfo } from "@/api/merchandise";

export default {
    data() {
        return {
            searchForm: {
            id: null,
            merchandise: '',
            minPrice: null,
            maxPrice: null,
            affiliation: '',
            status: '',
            type: '',
            time: '' // 时间范围
        },
            typeList: [], // 表格数据
            listLoading: true, // 加载状态
            dialogFormVisible: false, // 新增对话框显示状态
            pageNum: 1, // 当前页码
            pageSize: 5, // 每页条数
            total: 0, // 数据总条数
            form: {
               // itemTypeCode: '',
               merchandise: '',
                category: '',
                price: '',
                status: 'Y',
                parentTypeId: 0,
                image: ''
            }, // 表单数据
            parentTypes: [], // 父分类数据
        };
    },
    created() {
        this.fetchData(); // 初始化加载数据
    },
    methods: {

        viewDetails(row) {
        this.$router.push({ 
            name: 'MerchandiseDetails', // 路由名称
            params: { id: row.id } // 传递商品 ID
        });
    },
        // 获取表格数据
        // 获取表格数据
        fetchData(params = {}) {
         //   this.total = response.data.total; // 设置总条数

    this.listLoading = true;

    // 合并分页参数和搜索条件
    const queryParams = {
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        
        merchandise: this.searchForm.merchandise,
        minPrice: this.searchForm.minPrice,
        maxPrice: this.searchForm.maxPrice,
        affiliation: this.searchForm.affiliation,
        status: this.searchForm.status,
        type: this.searchForm.type,
        endTime: this.searchForm.time[1] || null, // 时间范围结束
        startTime:this.searchForm.time[0] || null, // 时间范围开始
        parentTypeId: this.searchForm.parentTypeId


    };

    getList(queryParams)
        .then(response => {
            console.log(response.data.searchInfo); // 打印接口返回数据
            this.typeList = response.data.searchInfo; // 设置表格数据
            this.total = response.data.total; // 设置总条数
            this.listLoading = false; // 关闭加载状态
        })
        .catch(error => {
            console.error('请求出错:', error);
            this.listLoading = false; // 关闭加载状态
        });
},
//搜素
handleSearch() {
    const params = {
        id: this.searchForm.id,
        merchandise: this.searchForm.merchandise,
        minPrice: this.searchForm.minPrice,
        maxPrice: this.searchForm.maxPrice,
        affiliation: this.searchForm.affiliation,
        status: this.searchForm.status,
        type: this.searchForm.type,
        startTime: this.searchForm.time[0] || null, // 时间范围开始
        endTime: this.searchForm.time[1] || null   // 时间范围结束
    };

    this.fetchData(params); // 调用 fetchData 方法，传递搜索条件
},
        // 新增操作
        handleAdd(index, row) {
            this.dialogFormVisible = true; // 打开新增对话框
            this.resetForm(); // 重置表单数据
        },
        // 提交新增数据
        addType() {
            const formData = new FormData();
    formData.append("merchandise", this.form.merchandise);
    formData.append("price", this.form.price);
    formData.append("packingFee", this.form.packingFee);
    formData.append("inventory", this.form.inventory);
    formData.append("soldMonthly", this.form.soldMonthly);
    formData.append("affiliation", this.form.affiliation);
    formData.append("status", this.form.status);
    formData.append("file", this.form.image); // 图片文件
            addType(this.form).then((response) => {
                if (response.code == 200) {
                    this.$message({
                        type: "success",
                        message: "新增成功!",
                    });
                    this.dialogFormVisible = false; // 关闭对话框
                    this.fetchData(); // 刷新表格数据
                }
            });
        },

         // 图片上传处理
         handleUpload(file) {
            const formData = new FormData();
            formData.append('file', file.file); // 将图片文件添加到 FormData
            // 调用上传接口
            return this.$axios.post('/upload', formData, {
                headers: { 'Content-Type': 'multipart/form-data' }
            });
        },
      // 图片上传成功回调
handleUploadSuccess(response, file) {
    if (response.code == 200) {
        this.form.imageFile = file.raw; // 保存文件对象
        this.$message.success("图片上传成功！");
    } else {
        this.$message.error("图片上传失败！");
    }
},
        // 图片上传失败回调
        handleUploadError() {
            this.$message.error('图片上传失败！');
        },
        // 重置表单数据
        resetForm() {
    this.form = {
       // itemTypeCode: "",
       merchandise: "",
        price: null,
        packingFee: null,
        inventory: null,
        soldMonthly: null,
        affiliation: "",
        status: "Y",
        imageFile: null, // 重置图片文件
    };
},
        // 删除操作
        handleDelete(index, row) {
            this.$confirm("此操作将永久删除该记录, 是否继续?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            })
                .then(() => {
                    deleteType(row.id).then(() => {
                        this.$message({
                            type: "success",
                            message: "删除成功!",
                        });
                        this.fetchData(); // 刷新表格数据
                    });
                })
                .catch(() => {
                    this.$message({
                        type: "info",
                        message: "已取消删除",
                    });
                });
        },
        // 编辑操作（可扩展）
        handleEdit(index, row) {
            this.dialogFormVisible = true; // 打开对话框
            this.form = { ...row }; // 填充表单数据
        },
        // 重置表单数据
        resetForm() {
            this.form = {
              //  itemTypeCode: '',
                merchandise: '',
                category: '',
                price: '',
                status: 'Y',
                parentTypeId: 0
            };
        },
        // 分页大小改变
        handleSizeChange(size) {
            this.pageSize = size;
            this.fetchData();
        },
        // 当前页码改变
        handleCurrentChange(page) {
            this.pageNum = page;
            this.fetchData();
        },
    },
};
</script>